/*
 * clock.c
 *
 *  Created on: Feb 4, 2012
 *      Author: daniel
 */

#include "clock.h"

#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <SDL_ttf.h>

static char timestr[20];
static SDL_Color timecolour;
static fonts_t* fonts;
static bool timehaschanged;

static void create(fonts_t* f) {
	memset(&timecolour, 0, sizeof(timecolour));
	fonts = f;
}

static int lastsecond = -1;
static SDL_Surface* timesurface = NULL;

static void render(SDL_Surface* surface, unsigned delta) {
	SDL_FillRect(surface, NULL, 0xFFFFFFFF);
	SDL_Rect dest;
	dest.y = (RENDERER_HEIGHT - timesurface->h) / 2;
	dest.x = (surface->w - timesurface->w) - dest.y;
	SDL_BlitSurface(timesurface, NULL, surface, &dest);
}

static bool shouldrender() {
	return true;
}

static void update() {
	time_t tt = time(NULL );
	struct tm *tmm = localtime(&tt);

	if (lastsecond == -1 || lastsecond != tmm->tm_sec) {
		snprintf(timestr, sizeof(timestr), "%02d:%02d:%02d %d/%d/%d", tmm->tm_hour, tmm->tm_min, tmm->tm_sec,
				tmm->tm_mday, tmm->tm_mon + 1, tmm->tm_year + 1900);
		if (timesurface != NULL ) {
			SDL_FreeSurface(timesurface);
		}
		timesurface = TTF_RenderText_Blended(fonts->large, timestr, timecolour);
		lastsecond = tmm->tm_sec;
		timehaschanged = true;
	}
	else
		timehaschanged = false;
}

static bool needstorender() {
	return timehaschanged;
}

static void dispose() {
	if (timesurface != NULL ) {
		SDL_FreeSurface(timesurface);
	}
}

const renderer_t clockrenderer = { "clock", //
		create, //
		update, //
		shouldrender, //
		needstorender, //
		render, //
		dispose };
